package com.woniu.after.util;

import com.woniu.after.entity.MinioProperties;
import com.woniu.common.util.ResponseData;
import com.woniu.common.util.ResponseEnum;
import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;

@Slf4j
@Component
public class MinioUtils {

    @Autowired
    private MinioClient minioClient;

    @Autowired
    private MinioProperties minioProperties;

    /**
     * 创建bucket
     */
    public void createBucket(String bucketName) {

        BucketExistsArgs bucketExistsArgs = BucketExistsArgs.builder().bucket(bucketName).build();
        MakeBucketArgs makeBucketArgs = MakeBucketArgs.builder().bucket(bucketName).build();
        try {
            // 判断存储桶是否存在
            if (minioClient.bucketExists(bucketExistsArgs)){
                return;
            }
            minioClient.makeBucket(makeBucketArgs);
        } catch (Exception e) {
            log.error("创建桶失败：{}", e.getMessage());
            throw new RuntimeException(e);
        }
    }

    /**
     * 上传文件
     * @param file
     * @param bucketName 桶名
     * @return
     * @throws Exception
     */
    public ResponseData<?> uploadFile(MultipartFile file, String bucketName) throws Exception {
        // 判断上传文件是否为空
        if (null == file || 0 == file.getSize()) {
            return new ResponseData<>().fail(ResponseEnum.FAIL);
        }

        // 创建桶，桶存在则不创建
        createBucket(bucketName);

        // 获取传的文件名
        String originalFilename = file.getOriginalFilename();
        // 新的文件名 = 存储桶名称 _ 时间戳.后缀名
        String newFileName = bucketName + "_" + System.currentTimeMillis() + originalFilename.substring(originalFilename.lastIndexOf("."));

        // 开始上传
        InputStream inputStream = file.getInputStream();
        PutObjectArgs args = PutObjectArgs.builder().bucket(bucketName).object(newFileName)
                .stream(inputStream, inputStream.available(), -1).build();
        //上传服务中
        minioClient.putObject(args);
        // 获取图片路径 minio服务器地址/桶名/文件名
        String imgPath = minioProperties.getEndpoint() + "/" + bucketName + "/" + newFileName;
        return new ResponseData<>().ok(imgPath);
    }
}
